package com.wdg.template.service.impl;

import com.wdg.template.controller.req.TemplateReq;
import com.wdg.template.convert.TemplateConvert;
import com.wdg.template.entity.TemplateEntity;
import com.wdg.template.repository.TemplateRepositoryI;
import com.wdg.template.service.TemplateServiceI;
import com.wdg.template.service.dto.TemplateDTO;
import com.wdg.utils.IdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class TemplateServiceImpl implements TemplateServiceI {

    @Autowired
    private TemplateRepositoryI templateRepositoryI;

    @Override
    public TemplateDTO getUserByPhoneNumber(String phoneNumber) {
        return TemplateConvert.INS.entity2DTO(templateRepositoryI.findByPhoneNumber(phoneNumber));
    }

    @Override
    public TemplateDTO login(TemplateReq templateReq) {
        TemplateEntity templateEntity = templateRepositoryI.findByPhoneNumber(templateReq.getPhoneNumber());
        if (Objects.isNull(templateEntity)){
            Long id = IdGeneratorUtil.nextId();
            templateEntity = TemplateEntity.create(id);
            templateEntity.setLastLoginTime(System.currentTimeMillis());
            TemplateConvert.INS.req2Entity(templateReq, templateEntity);
            templateRepositoryI.save(templateEntity);
        }else {
            templateEntity.setLastLoginTime(System.currentTimeMillis());
            templateRepositoryI.update(templateEntity);
        }
        return TemplateConvert.INS.entity2DTO(templateEntity);
    }
}
